package com.samphanie.auiu.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.samphanie.auiu.auth.service.IRoleService;
import com.samphanie.auiu.common.dto.RoleDto;
import com.samphanie.auiu.mbg.mapper.RoleMapper;
import com.samphanie.auiu.mbg.model.SysRole;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Dries
 * @email 1451691457@qq.com
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, SysRole> implements IRoleService {


    @Override
    public Set<SysRole> findByAuthorityIn(Set<String> authority) {
        return null;
    }

    @Override
    public Optional<SysRole> findOptionalByAuthority(String authority) {
        return Optional.ofNullable(baseMapper.selectOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, authority)
        ));
    }

    @Override
    public Optional<SysRole> findOptionalByRoleName(String roleName) {
        return Optional.ofNullable(baseMapper.selectOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, roleName)
        ));
    }

    @Override
    public boolean add(RoleDto roleDto) {
        val role = new SysRole();
        BeanUtils.copyProperties(roleDto, role);
        return save(role);
    }

    @Override
    public List<RoleDto> listRoleList() {
        val list = list(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::isStatus, true)
                .orderByDesc(SysRole::getSort)
                .orderByDesc(SysRole::getCreateTime)
        );
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(item -> {
                val roleDto = new RoleDto();
                BeanUtils.copyProperties(item, roleDto);
                return roleDto;
            }).collect(Collectors.toList());
        }
        return null;
    }
}
